package general

import (
	"context"
	"github.com/minio/minio-go/v7"
	"github.com/pkg/errors"
	"mime/multipart"
	"yangming-college/app/general/cmd/v1/api/internal/svc"
	"yangming-college/app/general/cmd/v1/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UploadLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UploadLogic {
	return &UploadLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UploadLogic) Upload(file multipart.File, fileHeader *multipart.FileHeader) (resp *types.UploadResp, err error) {
	minioClient := l.svcCtx.MinioClient
	//file name
	fileName := fileHeader.Filename
	//判断bucket是否存在
	found, err := minioClient.BucketExists(l.ctx, l.svcCtx.Config.Minio.BucketName)
	if err != nil {
		logx.WithContext(l.ctx).Errorf("Failed to Minio UploadImg bucket err:%v ", err)
		return nil, errors.Wrapf(err, "general v1 api Upload error 1")
	}

	// 存在bucket则不需要创建bucket
	if !found {
		err = minioClient.MakeBucket(l.ctx, l.svcCtx.Config.Minio.BucketName, minio.MakeBucketOptions{Region: l.svcCtx.Config.Minio.Location})
		if err != nil {
			logx.WithContext(l.ctx).Errorf("Failed to Minio Create Bucket err:%v ", err)
			return nil, errors.Wrapf(err, "general v1 api Upload error 2")
		}
	}

	_, err = minioClient.PutObject(l.ctx, l.svcCtx.Config.Minio.BucketName, fileName, file, int64(fileHeader.Size), minio.PutObjectOptions{
		ContentType: "application/text", //设置文件类型为二进制流（可根据实际情况修改）application/octet-stream
	})
	if err != nil {
		logx.WithContext(l.ctx).Errorf("Failed to Minio Save Image err:%v", err)
		return nil, errors.Wrapf(err, "general v1 api Upload error 3")
	}
	return &types.UploadResp{
		File: "http://" + l.svcCtx.MinioClient.EndpointURL().Host + "/" + l.svcCtx.Config.Minio.BucketName + "/" + fileName,
	}, nil
	return
}
